package com.xx.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import com.xx.entity.Document;
import com.xx.util.DBHelp;
import com.xx.util.DateUtil;
import com.xx.util.Pager;
import com.xx.util.RowMapper;

public class DocumentDao {

	DBHelp<Document> db = new DBHelp<Document>();

	public Document finDocument(String id) {

		String sql = "select id,title,content,createtime,t_employee_id,t_project_id from t_document where id=?";
		return db.executeQueryForObject(sql, new DocumentMapper(), id);
	}

	public int getMessageCount(String projectid) {
		String sql = "select count(*) from t_document where t_project_id = ? ";
		return db.executeQueryForCount(sql, projectid);
	}

	public Pager<Document> findDocuments(String id, int num) {

		Pager<Document> pager = new Pager<Document>(num, getMessageCount(id));

		String sql = "select id,title,content,createtime,t_employee_id,t_project_id from t_document where t_project_id=?  ORDER BY createtime DESC  limit ?,?";
		List<Document> Documents = db.executeQueryForList(sql,
				new DocumentMapper(), id, pager.getStartIndex(),
				pager.getPageSize()); //
		// executeQueryForList(sql, new
		// MessageMappe(),id,pager.getStartIndex(),pager.getPageSize());

		pager.setResult(Documents);

		return pager;

	}

	public void insertDocument(Document doc) {

		String sql = "insert into t_document(id,title,content,createtime,t_project_id,t_employee_id) value(?,?,?,?,?,?)";
		db.executeSQL(sql, doc.getId(), doc.getTitle(), doc.getContent(),
				doc.getCreatetime(), doc.getProjectid(), doc.getEmployeeid());
	}

	public class DocumentMapper implements RowMapper<Document> {

		public Document mapperRow(ResultSet rs) throws SQLException {
			Document dou = new Document();
			dou.setId(rs.getString("id"));
			dou.setTitle(rs.getString("title"));
			dou.setContent(rs.getString("content"));
			dou.setCreatetime(rs.getString("createtime"));
			dou.setEmployeeid(rs.getString("t_employee_id"));
			dou.setProjectid(rs.getString("t_project_id"));
			LoginDao loDao = new LoginDao();
			dou.setEmployee(loDao.findObject(rs.getString("t_employee_id")));
			try {
				String state = DateUtil.times(rs.getString("createtime"), loDao
						.findObject(rs.getString("t_employee_id"))
						.getUsername());
				dou.setState(state);

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return dou;

		}
	}

	public void updates(String did, String title, String content) {
		String sql = "update t_document set title=?,content=? where id=? ";
		db.executeSQL(sql, title, content, did);

	}

	public void dels(String did) {
		String sql = "delete from t_document where id=?";
		db.executeSQL(sql, did);

	}

}
